<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select
              v-model="q.cate_id"
              placeholder="请选择分类"
              size="small"
            >
              <el-option
                :label="item.name"
                v-for="item in cateList"
                :key="item.id"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small">筛选</el-button>
            <el-button type="info" size="small">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button
          type="primary"
          size="small"
          class="btn-pub"
          @click="showPubDialogFn"
          >发表文章</el-button
        >
      </div>
      <!-- 文章表格区域 -->
      <el-table :data="artList" style="width: 100%" border stripe>
        <el-table-column
          type="index"
          label="序号"
          width="100"
        ></el-table-column>
        <el-table-column label="文章标题" prop="title"></el-table-column>
        <el-table-column width="100px" label="分类" prop="cate_id">
          <template v-slot="{ row }">
            <template v-for="item in cateList">
              <el-tag v-if="item.id == row.cate_id" :key="item.id">{{
                item.name
              }}</el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="发表时间" prop="pub_date">
          <template v-slot="{ row }">
            <span>{{ $formatDate(row.pub_date) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="state">
          <template v-slot="{ row }">
            <el-tag v-if="row.state == '草稿'" type="danger">{{
              row.state
            }}</el-tag>
            <el-tag v-else type="success">{{ row.state }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="user_right" label="删除状态" prop="is_delete">
          <template v-slot="{ row }">
            <el-tag v-if="row.is_delete == 1" type="danger"> 已删除</el-tag>
            <el-tag v-else type="success">未删除</el-tag>
          </template>
        </el-table-column>
        <el-table-column width="250px" label="操作">
          <template v-slot="{ row }">
            <el-button type="info" size="mini" @click="showDetailFn(row.id)"
              >详细</el-button
            >
            <el-button type="success" size="mini" @click="editFn(row.id)">编辑</el-button>
            <el-button type="warning" size="mini" @click="removeFn(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChangeFn"
        @current-change="handleCurrentChangeFn"
        :current-page.sync="q.pagenum"
        :page-sizes="[2, 3, 5, 10]"
        :page-size.sync="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 发布文章 -->
    <el-dialog
      fullscreen
      :visible.sync="pubDialogVisible"
      :before-close="handleClose"
      @close="pubDialogClose"
    >
      <el-form
        :model="pubForm"
        label-width="100px"
        ref="pubFormRef"
        :rules="pubFormRuls"
      >
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <el-select
            @blur="selectRuls"
            v-model="pubForm.cate_id"
            placeholder="请选择分类"
            style="width: 100%"
          >
            <el-option
              :label="item.name"
              v-for="item in cateList"
              :key="item.id"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章封面">
          <el-upload
            class="avatar-uploader"
            action="http://upload-z2.qiniup.com "
            ref="upload"
            list-type="picture-card"
            :auto-upload="false"
            :limit="1"
            :data="uploadData"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :on-change="handleChange"
            :on-exceed="handleExceed"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <template>
            <el-tabs type="border-card" v-model="activeName">
              <el-tab-pane label="QuillEditor" name="QuillEditor">
                <quill-editor
                  class="ql-editor"
                  v-model="pubForm.content"
                  @blur="question"
                ></quill-editor>
              </el-tab-pane>
              <el-tab-pane label="MavonEditor" name="MavonEditor">
                <mavon-editor
                  v-model="content"
                  ref="md"
                  @imgAdd="imgAddFn"
                  @imgDel="imgDelFn"
                  boxShadow
                ></mavon-editor>
              </el-tab-pane>
            </el-tabs>
          </template>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="pubDialogVisible = false">取 消</el-button>
        <el-button type="success" @click="pubArticleFn('草稿')"
          >存为草稿</el-button
        >
        <el-button type="primary" @click="pubArticleFn('已发布')"
          >发布</el-button
        >
      </span>
    </el-dialog>
    <!-- 文章详细 -->
    <el-dialog
      title="提示"
      :visible.sync="detailDialogVisible"
      width="80%"
      center
    >
      <span>
        <h1 class="title">{{ artDetail.title }}</h1>

        <div class="info">
          <span>作者：{{ nickname || username }}</span
          ><br />
          <span>发布时间：{{ $formatDate(artDetail.pub_date) }}</span
          ><br />
          <span
            >所属分类：
            <template v-for="item in cateList">
              <el-tag v-if="item.id == artDetail.cate_id" :key="item.id">{{
                item.name
              }}</el-tag>
            </template></span
          ><br />
          <span>状态：{{ artDetail.state }}</span>
        </div>
        <!-- 分割线 -->
        <el-divider></el-divider>

        <!-- 文章的封面 -->
        <img width="60%" :src="artDetail.cover_img" alt="" />

        <!-- 文章的详情 -->
        <mavon-editor
          v-if="artDetail.editor === 'MavonEditor'"
          v-model="artDetail.content"
          default-open="preview"
          :editable="false"
          :subfield="false"
          :toolbarsFlag="false"
        ></mavon-editor>
        <div v-else v-html="artDetail.content" class="detail-box"></div>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
    <!-- 修改文章 -->
    <el-dialog
      width="90%"
      :visible.sync="editDialogVisible"
      :before-close="editDialogHandleClose"
      @close="editDialogClose"
    >
      <el-form
        :model="artDetail"
        label-width="100px"
        ref="editFormRef"
        :rules="pubFormRuls"
      >
        <el-form-item label="文章标题" prop="title">
          <el-input
            disabled
            v-model="artDetail.title"
            placeholder="请输入标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
            <template v-for="item in cateList">
              <el-input disabled v-if="item.id == artDetail.cate_id" :key="item.id" v-model="item.name"></el-input>
            </template>
        </el-form-item>
        <el-form-item label="文章封面" prop="cover_img">
            <img :src="artDetail.cover_img" class="cover-img" />
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <template v-if="artDetail.editor === 'MavonEditor'">
            <mavon-editor
              v-model="artDetail.content"
              ref="md"
              @imgAdd="imgAddFn"
              @imgDel="imgDelFn"
              boxShadow
            ></mavon-editor>
          </template>
          <template v-else>
            <quill-editor
              class="ql-editor"
              v-model="artDetail.content"
              @blur="question"
            ></quill-editor>
          </template>

        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="pubDialogVisible = false">取 消</el-button>
        <el-button @click="updateArtFn(artDetail.id)" type="primary">保存文章</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getArtCateListAPI,
  getTokenAPI,
  addArticleAPI,
  getArticleListAPI,
  getArticleDetailAPI,
  delArticleAPI,
  upLoadImgAPI,
  updateArtticleAPI
} from '@/api'
import { mapGetters } from 'vuex'
export default {
  name: 'ArtList',
  computed: {
    ...mapGetters(['username', 'nickname', 'user_right'])
  },
  data () {
    return {
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 5,
        cate_id: '',
        state: ''
      },
      pubDialogVisible: false,
      detailDialogVisible: false,
      pubForm: {
        // 表单的数据对象
        title: '',
        cate_id: '',
        content: '',
        value: '',
        cover_img: null,
        state: '',
        editor: this.activeName
      },
      pubFormRuls: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          {
            min: 1,
            max: 30,
            message: '文章标题的长度为1-30个字符',
            trigger: 'blur'
          }
        ],
        cate_id: [
          {
            required: true,
            message: '请选择文章分类',
            trigger: ['blur', 'change']
          }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ]
      },
      cateList: [],
      artDetail: {}, // 文章详细内容
      uploadData: { key: '', token: '' },
      isSelectCoverImg: false,
      artList: [], // 文章的列表数据
      total: 0, // 总数据条数
      activeName: 'MavonEditor',
      content: '',
      editDialogVisible: false
    }
  },
  methods: {
    // 弹窗关闭前的回调
    async handleClose (done) {
      const confirmResult = await this.$confirm(
        '此文章内容没保存，可能导致永久丢失，是否确定?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      // 点击了取消
      if (confirmResult === 'cancel') return
      // 点击了确定
      done()
    },
    showPubDialogFn () {
      this.pubDialogVisible = true
    },
    // 获取文章分类列表
    async getCateListFn () {
      const { data: res } = await getArtCateListAPI()
      if (res.status !== 0) return this.$message.error(res.message)
      this.cateList = res.data
    },
    // 选择图片
    selCoverFn () {
      // 触发 input 的原生事件
      this.$refs.iptFileRef.click()
    },
    // 图片上传之前的触发事件
    async beforeAvatarUpload (file) {
      // this.getUploadToken()
      const { data: res } = await getTokenAPI()
      this.uploadData.token = res.token
      this.uploadData.key = this.randomCoding(6) + file.uid + file.name
    },
    // 图片上传成功后的钩子函数
    handleAvatarSuccess (res) {
      this.pubForm.cover_img = 'http://rlj4znpmi.hn-bkt.clouddn.com/' + res.key
    },
    // 随机产生字母
    randomCoding (ln) {
      const result = []
      for (let i = 0; i < ln; i++) {
        const ranNum = Math.ceil(Math.random() * 25)
        result.push(String.fromCharCode(65 + ranNum))
      }
      return result.join('')
    },
    // 封面图的放大、删除事件
    handlePictureCardPreview () {},
    handleRemove () {},
    // 保存文章
    pubArticleFn (state) {
      // 开始上传封面图片
      this.pubForm.state = state
      this.pubForm.editor = this.activeName
      if (!this.isSelectCoverImg) return this.$message.error('请选择封面')
      this.$refs.upload.submit()
      const s = setInterval(async () => {
        if (this.pubForm.cover_img) {
          clearInterval(s)
          if (this.content !== '') {
            this.pubForm.content = this.$refs.md.d_render
            this.pubForm.value = this.$refs.md.d_value
            console.log('value', this.pubForm.value)
          }
          const { data: res } = await addArticleAPI(this.pubForm)
          if (res.status !== 0) return this.$message.error(res.message)
          this.$message.success(res.message)
          this.pubDialogVisible = false
          this.getArticleList()
        }
      }, 500)
    },
    // quillEditor 的验证规则触发事件
    question () {
      this.$refs.pubFormRef.validateField('content')
    },
    // 单独触发 el-select 的验证规则
    selectRuls () {
      this.$refs.pubFormRef.validateField('cate_id')
    },
    // 选完图片后触发的函数
    handleChange () {
      this.isSelectCoverImg = true
    },
    // 文件超出个数限制时的钩子
    handleExceed () {
      this.$message.error('封面图只允许上传一张图')
    },
    // 弹窗关闭后清空表单
    pubDialogClose () {
      this.$refs.pubFormRef.resetFields()
    },
    async getArticleList () {
      const { data: res } = await getArticleListAPI(this.q)
      if (res.status !== 0) return this.$message.error(res.message)
      this.artList = res.data
      this.total = res.total
    },
    // pageSize 发生了变化
    handleSizeChangeFn (newSize) {
      // 为 pagesize 赋值
      this.q.pagesize = newSize
      // 默认展示第一页数据
      this.q.pagenum = 1
      // 重新发起请求
      this.getArticleList()
    },
    // 页码值发生了变化
    handleCurrentChangeFn (newPage) {
      // 为页码值赋值
      this.q.pagenum = newPage
      // 重新发起请求
      this.getArticleList()
    },
    // 获取文章详细
    async showDetailFn (id) {
      const { data: res } = await getArticleDetailAPI(id)
      this.artDetail = res.data
      this.detailDialogVisible = true
    },
    // 通过id 删除文章
    async removeFn (id) {
      const confirm = await this.$confirm('确定删除该文章吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      // 点击了取消以及其他错误
      if (confirm === 'cancel') return this.$message.info('操作已取消')
      // 点击确定
      const { data: res } = await delArticleAPI(id)
      if (res.status !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      this.getArticleList()
    },
    // mavon-editor 上传图片并显示
    async imgAddFn (name, file) {
      const formData = new FormData()
      formData.append('files', file)
      const { data: res } = await upLoadImgAPI(formData)
      if (res.status !== 0) return this.$message(res.message)
      this.$refs.md.$img2Url(name, res.data.url)
    },
    imgDelFn (pos) {},
    // 文章编辑弹窗的关闭提示
    async editDialogHandleClose (done) {
      const confirmResult = await this.$confirm(
        '此文章内容没保存，可能导致永久丢失，是否确定?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      // 点击了取消
      if (confirmResult === 'cancel') return
      // 点击了确定
      done()
    },
    //
    editDialogClose () {
      this.$refs.editFormRef.resetFields()
    },
    //
    async editFn (id) {
      const { data: res } = await getArticleDetailAPI(id)
      this.artDetail = res.data
      this.artDetail.content = res.data.value ? res.data.value : res.data.content
      this.editDialogVisible = true
    },
    // 更新文章
    async updateArtFn (id) {
      const { data: res } = await updateArtticleAPI(this.artDetail.content, id)
      console.log(res)
      if (res.status !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      this.editDialogVisible = false
    }
  },
  created () {
    // 获取文章分类
    this.getCateListFn()
    this.getArticleList()
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
::v-deep .ql-editor {
  min-height: 300px;
  padding: 0;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #7c7c7c;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar1 {
  width: 178px;
  height: 178px;
  display: block;
}
.el-pagination {
  margin-top: 15px;
}
</style>
